/*
package com.air.thread;

import com.air.util.UnsafeInstance;
import lombok.extern.slf4j.Slf4j;
import sun.misc.Unsafe;

import java.util.concurrent.CyclicBarrier;

*/
/**
 * @author shent
 *//*

@Slf4j
public class CASDemo {
    private volatile int state = 0;
    //线程栅栏,用于模拟5个线程同时执行
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);
    //创建本类的实例,用户模拟测试
    private static CASDemo casDemo = new CASDemo();

    public static void main(String[] args) {
        new Thread(new Worker(), "t-0").start();
        new Thread(new Worker(), "t-1").start();
        new Thread(new Worker(), "t-2").start();
        new Thread(new Worker(), "t-3").start();
        new Thread(new Worker(), "t-4").start();
    }

    static class Worker implements Runnable {
        @Override
        public void run() {
            log.info("进入:" + Thread.currentThread().getName());
            try {
                //让5个线程再次停顿,同时并发执行
                cyclicBarrier.await();
                if (casDemo.compareAndSwapState(0, 1)) {
                    log.info("获取锁:" + Thread.currentThread().getName());
                } else {
                    log.info("没有获取锁:" + Thread.currentThread().getName());
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

        }
    }

    */
/**
     * 自定义cas原子操作
     * 改变int类型的值
     *
     * @param oldValue 线程工作内存中的旧值
     * @param newValue 要替换的新值
     * @return 是否成功
     *//*

    public final boolean compareAndSwapState(int oldValue, int newValue) {
        return unsafe.compareAndSwapInt(this, stateOffset, oldValue, newValue);
    }

    private static final Unsafe unsafe = UnsafeInstance.reflectGetUnsafe();
    private static long stateOffset;

    //类加载时被调用
    static {
        try {
            //首先取得类里面,要改变的值的偏移量
            stateOffset = unsafe.objectFieldOffset(CASDemo.class.getDeclaredField("state"));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
*/
